import {useState} from 'react'
import {Space,Input,Image,Button,message} from 'antd'
import { useRef } from 'react'
import {addBanner} from '@/api/banner'
import {useNavigate} from 'react-router-dom'
import { useMemo } from 'react'
export default function Add() {
  const [link,setLink] = useState('')
  const [alt,setAlt] = useState('')
  const [img,setImage] = useState('')
  const navigate = useNavigate()
  const file = useRef()
  // 上传图片的时候触发handleFile
  const handleFile = ()=>{
    const fileInfo = file.current.input.files[0]
    // 限制文件类型，必须是图片类型
    const typeRight = ['image/jpeg','image/jpg','image/png'].includes(fileInfo.type)
    // 限制图片大小
    const sizeRight = fileInfo.size / 1024 / 1024 < 2
    if(!typeRight){
      message.error('文件类型不正确')
      setImage('')
      return false
    }else if(!sizeRight){
      message.error('图片大小高于2M')
      setImage('')
      return false
    }

    // 可以通过FileReader对象将上传的图片转成base64位的地址存储到后端
    const reader = new FileReader()
    reader.readAsDataURL(fileInfo)
    reader.onload = function(){
      setImage(reader.result)
    }
  }

  // 添加轮播图方法
  const onAdd = ()=>{
    addBanner({
      img,
      alt,
      link
    }).then(()=>{
      message.success('添加轮播图成功！')
      navigate(-1)
    })
  }

  // 如果link/alt/img都必须填写后才可以添加轮播图
  const flag = useMemo(()=>{
    return link.trim().length === 0 || alt.trim().length === 0 || img.trim().length === 0
  },[link,alt,img])
  return (
    <Space direction='vertical'>
      <Input placeholder='link' value={link} onChange={e=>setLink(e.target.value)}/>
      <Input placeholder='alt' value={alt} onChange={e=>setAlt(e.target.value)}/>
      <Input type={'file'} ref={file} onChange={handleFile}/>
      <Input disabled placeholder='上传好的图片地址' value={img}/>
      <Image src={img}/>
      <Button disabled={flag} type='primary' onClick={onAdd}>添加轮播图</Button>
    </Space>
  )
}
